package com.speedy.course.ui

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.google.android.material.tabs.TabLayoutMediator
import com.speedy.course.constant.WeekDay
import com.speedy.course.databinding.FragmentHomeBinding

class HomeFragment : Fragment() {

    private var _binding: FragmentHomeBinding? = null

    private val binding get() = _binding!!

    companion object{
        private val titles = listOf("周一","周二","周三","周四","周五","周六","周日")
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        _binding = FragmentHomeBinding.inflate(inflater, container, false)

        initView()

        return binding.root
    }

    private fun initView() {

        binding.apply {

            viewPager.adapter = WeekPagerAdapter(childFragmentManager,lifecycle)

            TabLayoutMediator(tabLayout, viewPager) { tab, position ->
                tab.text = titles[position]
            }.attach()

            ivAdd.setOnClickListener {
                startActivity(Intent(activity,AddLessonActivity::class.java).apply {
                    putExtra("index",viewPager.currentItem)
                })
            }

        }

    }


    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}


class WeekPagerAdapter(
    fragmentManager: FragmentManager,
    lifecycle: Lifecycle
) : FragmentStateAdapter(fragmentManager, lifecycle) {

    private val weekList = mutableListOf<WeekFragment>()

    init {
        weekList.add(WeekFragment.newInstance(WeekDay.MONDAY))
        weekList.add(WeekFragment.newInstance(WeekDay.TUESDAY))
        weekList.add(WeekFragment.newInstance(WeekDay.WEDNESDAY))
        weekList.add(WeekFragment.newInstance(WeekDay.THURSDAY))
        weekList.add(WeekFragment.newInstance(WeekDay.FRIDAY))
        weekList.add(WeekFragment.newInstance(WeekDay.SATURDAY))
        weekList.add(WeekFragment.newInstance(WeekDay.SUNDAY))
    }




    override fun getItemCount(): Int {
        return weekList.size
    }

    override fun createFragment(position: Int): Fragment {
        return weekList[position]
    }

}
